<template>
  <div>
    <BreakSpace label="基本信息" :containerStyle="{ marginBottom: '10px' }"/>
    <FormPanel
      ref="baseInfo"
      :list="initFormBase"
      :cols="3"
      :labelWidth="170"
      :isSubmitBtn="false"
      :formType="handleType"
    />
    <div v-if="handleType === 'add'">
      <BreakSpace label="电池列表" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
      <FilterTable
        ref="tableBattery"
        columnsRef="tableBattery"
        selectionType="single"
        :columns="initDcColumn"
        :onSyncTableData="data => formData.batteries = data"
        :isSelectColumn="false"
        :isMemoryPagination="true"
        :onColumnsChange="columns => (this.initDcColumn = columns)"
        :onRowSelectChange="arr => (this.onChangeColumn = arr)"
      >
        <template slot="controls">
          <el-button v-if="handleType != 'show'" size="small" type="primary" icon="el-icon-plus" @click="openDcDialog">
            添加电池
          </el-button>
          <el-button v-if="handleType != 'show'" size="small" type="primary" icon="el-icon-plus" @click="addRow">
            添加一行
          </el-button>
        </template>
      </FilterTable>
    </div>
    <BaseDialog :visible.sync="visbleVehicle" title="车辆选择"
                :containerStyle="{ overflow: 'auto', paddingBottom: '60px' }"
                destroyOnClose>
      <add-vehicle
        selectionType="single"
        @selectArr="selectVehicleFun"
        @closeDialog='visbleVehicle = false'></add-vehicle>
    </BaseDialog>
    <BaseDialog :visible.sync="visibleDc" title="电池选择"
                :containerStyle="{ overflow: 'auto', paddingBottom: '60px' }"
                destroyOnClose>
      <add-battery
        selectionType="multiple"
        :params="getDcParams"
        @selectArr="selectDcFun"
        @closeDialog='visibleDc = false'></add-battery>
    </BaseDialog>
    <div class="dialogBottmView">
      <el-button @click="closeDialogTop()">返 回</el-button>
      <el-button v-if="handleType != 'show'" @click="saveDialog()" :loading="saveLoading" type="primary">
        保存
      </el-button>
      <el-button v-if="pageType == 'DLR1' && handleType !== 'show'" @click="saveDialog('T')" :loading="saveLoading"
                 type="primary">
        提报
      </el-button>
    </div>
  </div>
</template>
<script>
import {dictionary} from '@/utils/dictMixin';
import {
  postSaveBatteryRecycle,
  postUpdateStatusByIds,
  putBatteryRecycle
} from '@/api/partsmanage/batteryTrace/batteryRecycle';
import {getBatterySupplier} from '@/api/partsmanage/batteryTrace/batterySupplier';
import {dclxArr, dqArr, hsdldclbArr, hsnrArr, tyqylxArr} from './constant';
import addVehicle from '@/pages/partsmanage/purchaseManage/purchaseSubmit/addVehicle';
import {getDealerCompanyByCode} from '@/api/part/exchange/platform';
import addBattery from './addBattery';

export default {
  components: {
    addVehicle,
    addBattery,
  },
  props: {
    handleType: {
      type: String,
      default: 'add'
    },
    pageType: {
      type: String,
      default: ''
    },
    value: {
      type: Object,
      default: null
    }
  },
  mixins: [dictionary],
  data() {
    return {
      formData: {
        handOverStatus: 'W',
        vin: '',
        vehicleId: '',
        batterySpecies: '',
        batteries: []
      },
      initFormBase: this.initFormBaseFun(),
      initDcColumn: this.initDcColumnFun(),
      visbleVehicle: false,
      visibleDc: false,
      saveLoading: false,
    };
  },
  mounted() {
    this.getSupplier()
    //判断是新增，还是修改
    if (this.handleType == 'add') {
      getDealerCompanyByCode().then(res => {
        const dealerInfo = res.data
        this.formData.dealerCode = dealerInfo.dealerCode
        this.formData.dealerName = dealerInfo.dealerName
        this.formData.recoverUnitName = dealerInfo.dealerName
        this.formData.dealerAddr = dealerInfo.address
        this.init()
      })
    } else {
      this.formData = Object.assign({}, this.value.data);
      if (this.formData.leavePlant)
        this.formData.leavePlantName = this.formData.leavePlant.name;
      this.init();
      // getBatteryRecycleById(this.value.id).then(res => {
      //   if (res.resultCode === 200) {
      //     const data = Object.assign({}, this.formData, this.value.data, res.data);
      //     console.info(data)
      //     this.formData = data;
      //
      //   }
      // })
    }
  },
  computed: {
    getDcParams() {
      return {
        vin: this.formData.vin,
        vehicleId: this.formData.vehicleId,
        batterySpecies: this.formData.batterySpecies
      }
    },
    culFormData() {
      return this.formData
    }
  },
  methods: {
    //修改时，初始化页面数据
    init() {
      //循环为表单赋值
      this.initFormBase.forEach(x => {
        if (this.culFormData[x.fieldName]) {
          x.initialValue = this.culFormData[x.fieldName];
        }
      });
    },
    getSupplier() {
      getBatterySupplier({pageType: 'addBattery'}).then(res => {
        if (res.resultCode == 200) {
          const itemList = res.data.map(i => {
            return {
              text: i.name,
              value: i.id
            }
          })
          this.initFormBase.find(i => i.fieldName === 'batterySupplierId').itemList = itemList
        }
      })
    },
    //基本表单信息
    initFormBaseFun() {
      return [
        {
          type: 'INPUT',
          label: '电池回收登记单号',
          fieldName: 'recycleCode',
          placeholder: '请输入',
          hidden: this.handleType === 'add',
          initialValue: '',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入',
          initialValue: '',
          readonly: true,
          disabled: true,
          rules: [
            {required: true, trigger: 'change', message: '请输入'}
          ],
        },
        {
          type: 'INPUT',
          label: '经销商地址',
          fieldName: 'dealerAddr',
          placeholder: '请输入',
          initialValue: '',
          disabled: true,
          readonly: true,
          rules: [
            {required: true, trigger: 'change', message: '请输入'}
          ],
        },
        {
          type: 'INPUT',
          label: '统一社会信用代码',
          fieldName: 'recoverUnitCode',
          placeholder: '请输入',
          disabled: this.handleType !== 'add',
          initialValue: '',
          rules: [
            {required: true, trigger: 'change', message: '请输入'}
          ],
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          placeholder: '请选择',
          disabled: this.handleType !== 'add',
          readonly: true,
          initialValue: '',
          rules: [
            {required: true, trigger: 'change', message: '请选择'}
          ],
          change: val => {
            this.formData.vin = val
          },
          unitRender: () =>
            (<el-button icon="el-icon-search" onClick={() => this.visbleVehicle = true}></el-button>),
        },
        {
          type: 'SELECT',
          label: '回收内容',
          fieldName: 'batterySpecies',
          placeholder: '请选择',
          disabled: this.handleType !== 'add',
          initialValue: '',
          itemList: hsnrArr,
          change: val => {
            this.changeBatterySpecies(val);
          },
          rules: [
            {required: true, message: '请选择', trigger: 'change'},
          ]
        },
        {
          type: 'DATE',
          label: '回收日期',
          fieldName: 'storageDate',
          placeholder: '请输入',
          disabled: this.handleType !== 'add',
          initialValue: new Date(),
          format: 'yyyy-MM-dd',
          rules: [
            {required: true, trigger: 'change', message: '请选择回收日期'},
          ],
        },
        {
          type: 'SELECT',
          label: '电池供应商',
          fieldName: 'batterySupplierId',
          placeholder: '请选择',
          initialValue: '',
          itemList: [],
          rules: [
            {required: true, message: '请选择', trigger: 'change'},
          ]
        },
        {
          type: 'INPUT',
          label: '电池年限',
          fieldName: 'batteryYear',
          placeholder: '',
          initialValue: '',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '电池包编码',
          fieldName: 'batteryCode',
          placeholder: '请输入',
          disabled: true,
          hidden: this.handleType === 'add',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '电池模块编号',
          fieldName: 'batteryModuleCode',
          placeholder: '请输入',
          disabled: true,
          hidden: this.handleType === 'add',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '电芯编号',
          fieldName: 'batteryCellCode',
          placeholder: '请输入',
          disabled: true,
          hidden: this.handleType === 'add',
          initialValue: '',
        },
        {
          type: 'INPUT',
          label: '电池质量',
          fieldName: 'batteryWeight',
          placeholder: '请输入',
          disabled: this.handleType !== 'add',
          hidden: this.handleType === 'add',
          initialValue: '',
          unitRender: () => <span>kg</span>
        },
        {
          type: 'SELECT',
          label: '电池类别',
          fieldName: 'batteryType',
          placeholder: '请选择',
          disabled: this.handleType !== 'add',
          initialValue: '',
          itemList: dclxArr,
          rules: [
            {required: true, message: '请选择', trigger: 'change'},
          ]
        },
        {
          type: 'SELECT',
          label: '回收服务网点所在地区',
          fieldName: 'recoverUnitArea',
          placeholder: '请选择',
          itemList: dqArr,
          initialValue: '',
          rules: [
          {required: true, message: '请选择', trigger: 'change'},
        ]
        },
        {
          type: 'SELECT',
          label: '回收动力电池类别',
          fieldName: 'recoverBatteryLevel',
          placeholder: '请选择',
          initialValue: '',
          itemList: hsdldclbArr,
          rules: [
            {required: true, trigger: 'blur', message: '请输入'},
          ]
        },
        {
          type: 'BREAK_SPACE',
          label: '回收交接及退役信息',
          hidden: this.handleType !== 'show',
        },
        {
          type: 'INPUT',
          label: '去向厂商名称',
          fieldName: 'leavePlantName',
          placeholder: '请选择',
          initialValue: '',
          hidden: this.handleType !== 'show',
        },
        {
          type: 'INPUT',
          label: '去向厂商统一社会信用代码',
          fieldName: 'leavePlantCode',
          placeholder: '',
          hidden: this.handleType !== 'show',
          initialValue: '',
        },
        {
          type: 'INPUT',
          label: '退役厂商名称',
          fieldName: 'retiredPlantName',
          placeholder: '请输入',
          hidden: this.handleType !== 'show',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '退役厂商统一社会信用代码',
          fieldName: 'retiredPlantCode',
          placeholder: '请输入',
          hidden: this.handleType !== 'show',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '退役日期',
          fieldName: 'retiredDate',
          placeholder: '请输入',
          hidden: this.handleType !== 'show',
          initialValue: '',
        },
        {
          type: 'SELECT',
          label: '退役企业类型',
          fieldName: 'retireUnitType',
          placeholder: '请选择',
          initialValue: '',
          itemList: tyqylxArr,
          hidden: this.handleType !== 'show',
        },
      ];
    },
    //电池列表定义
    initDcColumnFun() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        ...this.handleType == 'show' ? [] : [{
          width: 100,
          title: '操作',
          dataIndex: 'column-action',
          render: props => {
            return (
              <div>
                <el-button disabled={this.handleType === 'show'} size="mini" type="text"
                           onClick={() => this.$refs.tableBattery.EXECUTE_DELETE([props.row])}>
                  删除
                </el-button>
              </div>
            );
          }
        }],
        {
          title: '电池包编码',
          dataIndex: 'batteryCode',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
        },
        {
          title: '电池模块编号',
          dataIndex: 'batteryModuleCode',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
        },
        {
          title: '电芯编号',
          dataIndex: 'batteryCellCode',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
        },
        {
          title: '电池质量（kg）',
          dataIndex: 'batteryWeight',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: this.handleType != 'show',
          editType: 'number',
          editPattern: /^[1-9]\d*(\.\d{0,2})?$/,
          editRequired: true,
          summation: true
        },
      ];
    },
    changeBatterySpecies(batterySpecies) {
      this.formData.batterySpecies = batterySpecies
    },
    /*选择车辆信息回调 */
    selectVehicleFun(arr) {
      const vehicle = arr[0]
      this.visbleVehicle = false
      this.formData.vehicleId = vehicle.id
      this.formData.vin = vehicle.vin
      this.initFormBase.find(i => i.fieldName === 'vin').initialValue = vehicle.vin
      this.initFormBase.find(i => i.fieldName === 'batteryYear').initialValue = ''
      if (vehicle.salesDate) {
        const cz = new Date().getTime() - new Date(vehicle.salesDate).getTime();
        if (cz > 0) {
          const days = cz / (24 * 60 * 60 * 1000)
          const years = parseInt(days / 365 + 1) //年限
          this.initFormBase.find(i => i.fieldName === 'batteryYear').initialValue = years
        }
      }
    },
    /* 打开添加电池维修记录Dialog */
    openDcDialog() {
      if (!this.getDcParams.vin) {
        this.$notify.error({title: '提示信息', message: '请先选择VIN'});
      } else if (!this.getDcParams.batterySpecies) {
        this.$notify.error({title: '提示信息', message: '请选择更换内容!'});
      } else {
        this.visibleDc = true;
      }
    },
    /* 添加一行 */
    addRow() {
      this.$refs.tableBattery.EXECUTE_INSERT([{
        batteryMaintenanceId: 0,
        batteryCode: '',
        batteryModuleCode: '',
        batteryCellCode: '',
        batteryWeight: '',
      }]);
    },
    /*选择电池信息回调 */
    selectDcFun(arr) {
      this.visibleDc = false;
      const addArr = arr.map(i => {
        const obj = {
          batteryMaintenanceId: i.id,
          batteryCode: i.oldCode || '',
          batteryModuleCode: i.oldModuleCode || '',
          batteryCellCode: i.oldCellCode || '',
          batteryWeight: '',
        }
        return obj
      });
      this.$refs.tableBattery.EXECUTE_INSERT(addArr);
    },
    //保存
    async saveDialog(status = 'C') {
      this.saveLoading = true;
      if (this.handleType == 'show' && status === 'T') {
        return this.tbHandle(status)
      }
      let [err, data] = await this.$refs.baseInfo.GET_FORM_DATA();
      if (err) {
      } else {
        this.formData = Object.assign({}, this.formData, data);
        const formData = {
          ...this.culFormData,
          status
        }
        let res;
        if (this.handleType === "add") { // 新增
          res = await postSaveBatteryRecycle(formData);
        } else { // 修改
          res = await putBatteryRecycle(formData);
        }
        if (res.resultCode === 200) {
          this.$notify.success({title: '提示信息', message: status == 'T' ? '提报成功' : '保存成功!'});
          // 重新加载
          this.closeDialog('refresh');
        }
      }
      this.saveLoading = false;
    },
    // 提报
    async tbHandle(status) {
      this.saveLoading = true
      const res = await postUpdateStatusByIds({
        status,
        ids: [this.formData.id]
      })
      if (res.resultCode == 200) {
        this.$notify.success({title: '提示信息', message: '提报成功'});
        this.closeDialog('refresh');
      }
      this.saveLoading = false
    },
    closeDialogTop(confirm) {
      if (confirm) {
        this.$confirm('确认关闭窗口吗？您所做的操作将不会被保存！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.closeDialog('closeDialog');
        })
      } else {
        this.closeDialog('closeDialog');
      }
    },
    //取消操作
    closeDialog(type) {
      this.$emit('close', type);
    }
  }
};
</script>

<style lang="less" scoped>
</style>
